package reflection;

import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;

public class Test04 {
    public static void main(String[] args) throws ClassNotFoundException, InstantiationException, IllegalAccessException, NoSuchMethodException, InvocationTargetException, NoSuchFieldException {
        Class<?> c1 = Class.forName("reflection.User");
        User user=(User)c1.newInstance();
        System.out.println(user);

        //通过构造器创建对象
        Constructor<?> declaredConstructor = c1.getDeclaredConstructor(String.class, int.class);
        User user2=(User)declaredConstructor.newInstance("钱江",187);
        user2.setName("打个");
        System.out.println(user2);

        //通过反射操作属性
        User user4=(User)c1.newInstance();
        Field name = c1.getDeclaredField("name");
        name.setAccessible(true);//关闭程序安全检测
        name.set(user4,"狂神3");
        System.out.println(user4.getName());
    }
}
